package mge.particles 
{
  import flash.display.Bitmap;
  import flash.display.Loader;
  import flash.display.LoaderInfo;
  import flash.display.MovieClip;
  import flash.events.Event;
  import flash.net.URLLoader;
  import flash.net.URLRequest;
  import mge.serialization.Serializer;
    
	/**
   * ...
   * @author ivan
   */
  public class ParticleSystemMovieClip extends MovieClip
  {
    [Inspectable(name="xml", defaultValue='')]
    public var xmlName:String = '';
    
    public function ParticleSystemMovieClip() 
    {
      addEventListener(Event.EXIT_FRAME, onExitFrame);
    }
    
    // First frame
    private function onExitFrame(e:Event):void
    {
      removeEventListener(Event.EXIT_FRAME, onExitFrame);
      
      var loader:Loader = new Loader();
      loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBitmapLoaded);
      loader.load(new URLRequest("particles.png"));
      // addChild(loader);
    }
    
    private function onBitmapLoaded(e:Event):void
    {
      var loader:Loader = Loader(e.target.loader);
      bitmap = Bitmap(loader.content);
      trace(bitmap);
      
      var xmlLoader:URLLoader = new URLLoader();      
      xmlLoader.addEventListener(Event.COMPLETE, initParticleSystem);
      
      trace("attempting to load '" + xmlName + "'");
      xmlLoader.load(new URLRequest(xmlName));
    }
    
    private function initParticleSystem(e:Event):void 
    {
      var xml:XML = new XML(e.target.data);
      trace("xml: " + xml);
      
      ps = new ParticleSystem(bitmap, this);
      ps.descriptor = new Serializer().deserialize(xml, Descriptor) as Descriptor;
      ps.fire();
      
      addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }
    
    private function onEnterFrame(e:Event):void
    {
      ps.update();
    }
    
    private var ps:ParticleSystem;
    private var bitmap:Bitmap;
  }

}